package com.mall.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.common.api.Code;
import com.mall.common.api.Result;
import com.mall.entity.*;
import com.mall.mapper.OmsCartItemMapper;
import com.mall.service.OmsCartItemService;
import com.mall.service.OmsOrderItemService;
import com.mall.service.OmsOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.units.qual.A;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

@RestController
@Api(tags = "OmsCartItemController", description = "购物车管理")
@RequestMapping("/cart")
public class OmsCartItemController
{
    @Resource
    private OmsCartItemService omsCartItemService;

    @Resource
    private OmsOrderService omsOrderService;

    @Resource
    private OmsOrderItemService omsOrderItemService;

    @ApiOperation(value = "根据会员id查询购物车内容")
    @GetMapping("/{memberId}")
    public Result getByMemberId(@PathVariable Long memberId) {
        List<OmsCartItem> list = new ArrayList<>();
        list = omsCartItemService.getByMemberId(memberId);
        Integer code = list !=null ? Code.GET_OK:Code.GET_ERR;
        String msg = list !=null ? "successful":"failed,please try again";
        return new Result(list,code,msg);
    }

    @ApiOperation(value = "新增或更新购物车")
    @PostMapping
    public Result save(@RequestBody OmsCartItem omsCartItem) {
        //如果重复添加同一件商品，不应该新增一个购物车条目，而是直接将数量加一
        Long productId = omsCartItem.getProductId();
        Long memberId = omsCartItem.getMemberId();
        boolean flag;
        OmsCartItem omsCartItem1 = omsCartItemService.getSame(memberId,productId);
        if(omsCartItem1!=null)
        {
            System.out.println("已有重复的");
            omsCartItem1.setQuantity(omsCartItem1.getQuantity()+omsCartItem.getQuantity());
            flag = omsCartItemService .save(omsCartItem1);
        }else{
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time = formatter.format(date);
            omsCartItem.setCreateDate(time);
            flag = omsCartItemService .save(omsCartItem);
        }
        return new Result(flag? Code.SAVE_OK: Code.SAVE_ERR,flag);
    }

    @ApiOperation(value = "修改购物车数量")
    @PostMapping("/setNum")
    public Result setNum(@RequestBody OmsCartItem omsCartItem) {
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = formatter.format(date);
        omsCartItem.setCreateDate(time);
        boolean flag = omsCartItemService .save(omsCartItem);
        return new Result(flag? Code.SAVE_OK: Code.SAVE_ERR,flag);
    }

    @PostMapping ("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        boolean flag = omsCartItemService.removeByIds(ids);
        return new Result(flag?Code.DELETE_OK: Code.DELETE_ERR,flag);
    }

    @ApiOperation("分页查询")
    @GetMapping("/page")
    public IPage<OmsCartItem> getPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String productName,
                                      @RequestParam Long memberId) {
        IPage<OmsCartItem> page = new Page<>(pageNum,pageSize);
        QueryWrapper<OmsCartItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("member_id", memberId);
        queryWrapper.like("product_name",productName);
        return omsCartItemService.page(page,queryWrapper);
    }

    @ApiOperation(value = "根据id删除购物车条款")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        boolean flag = omsCartItemService.delete(id);
        return new Result(flag?Code.DELETE_OK: Code.DELETE_ERR,flag);
    }

    @ApiOperation(value = "新版结算")
    @PostMapping("/getProductList")
    public Result getProductList(@RequestBody List<Long> ids){
        List<OmsCartItem> cartItemList = omsCartItemService.getByIds(ids);
        Integer code = cartItemList !=null ? Code.GET_OK:Code.GET_ERR;
        String msg = cartItemList !=null ? "successful":"failed,please try again";
        return new Result(cartItemList,code,msg);
    }

    @ApiOperation(value = "结算")
    @PostMapping("/settled")
    public Result settled(@RequestBody List<Long> ids){
        //1.结算后，先生成订单
        OmsOrder order = new OmsOrder();
        //2.根据购物车条目id获取购物车条目对象列表
        List<OmsCartItem> cartItemList = omsCartItemService.getByIds(ids);
        //3.将购物车条目的成员id赋值给订单
        Long memberId = cartItemList.get(0).getMemberId();
        order.setMemberId(memberId);
        //4.1获取当前时间+随机数生成订单sn，并将当前时间赋值给创建订单时间
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String orderSn = formatter.format(date);
        Random random = new Random();
        for(int i=0;i<10;i++)
        {
            orderSn +=  String.valueOf(random.nextInt(10));
        }
        order.setOrderSn(orderSn);
        order.setCreateTime(date);
        order.setMemberUsername(cartItemList.get(0).getMemberNickname());
        //4.2计算订单总金额
        BigDecimal amount = new BigDecimal(0);
        for(int i=0;i<cartItemList.size();i++)
        {
            BigDecimal quantity = new BigDecimal(cartItemList.get(i).getQuantity());
            amount = amount.add(cartItemList.get(i).getPrice().multiply(quantity));
        }
        order.setTotalAmount(amount);
        //5.将订单加入订单表中，并获取当前订单id
        omsOrderService.save(order);
        Long orderId = omsOrderService.getMax();
        //6.设置订单条目的属性，并将其加入列表中
        List<OmsOrderItem> list = new ArrayList<>();
        for(int i=0;i<cartItemList.size();i++)
        {
            OmsOrderItem orderItem = new OmsOrderItem();
            OmsCartItem cartItem = cartItemList.get(i);
            orderItem.setProductBrand(cartItem.getProductBrand());
            orderItem.setProductId(cartItem.getProductId());
            orderItem.setProductPic(cartItem.getProductPic());
            orderItem.setProductName(cartItem.getProductName());
            orderItem.setProductPrice(cartItem.getPrice());
            orderItem.setProductSn(cartItem.getProductSn());
            orderItem.setProductQuantity(cartItem.getQuantity());
            orderItem.setProductSkuCode(cartItem.getProductSkuCode());
            orderItem.setProductSkuId(cartItem.getProductSkuId());
            orderItem.setProductCategoryId(cartItem.getProductCategoryId());
            orderItem.setSpData(cartItem.getSpData());
            orderItem.setPromotionName("无优惠");
            orderItem.setPromotionAmount(BigDecimal.valueOf(0));
            orderItem.setCouponAmount(BigDecimal.valueOf(0));
            orderItem.setOrderId(orderId);
            orderItem.setOrderSn(orderSn);
            list.add(orderItem);
        }
        //7.将订单条目列表写入表中
        boolean flag = omsOrderItemService.saveBatch(list);
        //8.从购物车表中删除条目
//        boolean flag1 = omsCartItemService.removeByIds(ids);
        Integer code = orderId !=null ? Code.GET_OK:Code.GET_ERR;
        String msg = orderId !=null ? "successful":"failed,please try again";
        return new Result(orderId,code,msg);
    }

}
